<template>
	<view>
		<up-button type="warning" size="mini" @click="sendCode" class="send" :disabled="sending">
			{{ btnText }}
		</up-button>
	</view>
</template>

<script setup>
import { ref } from 'vue'
import { sendSmsCode } from '@/api/user.js'

// 定义手机号 prop
const props = defineProps({
	mobile: {
		type: String,
		required: true
	},
	checked: {
		type: Boolean,
		default: false
	}
})

const timer = ref(null)
const count = ref(120)
const sending = ref(false)
const btnText = ref('发送验证码')

const startCountdown = () => {
	sending.value = true
	btnText.value = `${count.value}s后重试`
	timer.value = setInterval(() => {
		count.value--
		btnText.value = `${count.value}s后重试`
		if (count.value <= 0) {
			clearInterval(timer.value)
			sending.value = false
			count.value = 120
			btnText.value = '发送验证码'
		}
	}, 1000)
}

const sendCode = async () => {
	if (sending.value) return
	if (!props.mobile) {
		uni.showToast({ title: '请输入手机号', icon: 'none' })
		return
	}
	if (!/^1[3-9]\d{9}$/.test(props.mobile)) {
		uni.showToast({ title: '请输入正确的手机号', icon: 'none' })
		return
	}
	if (props.checked == false) {
		uni.showToast({ title: '请先勾选同意协议', icon: 'none' })
		return
	}
	try {
		let res = await sendSmsCode(props.mobile, '5')
		// console.log('res===>', res);
		if (res.data) {
			uni.showToast({ title: '验证码发送成功', icon: 'none' })
			startCountdown()
		} else {
			uni.showToast({ title: '验证码发送失败', icon: 'none' })
		}
	} catch (e) {
		console.log(e)
		uni.showToast({ title: e?.msg || '发送失败', icon: 'none' })
	}
}
</script>

<style lang="scss" scoped></style>